package com.xiaoxu.spzx.manager.service.impl;

import cn.hutool.core.date.DateUtil;
import com.xiaoxu.common.exception.XiaoXuException;
import com.xiaoxu.spzx.manager.properties.MinioProperties;
import com.xiaoxu.spzx.manager.service.FileUploadService;
import com.xiaoxu.spzx.model.vo.common.ResultCodeEnum;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.UUID;


@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) {
        try {

            // 创建一个Minio的客户端对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioProperties.getEndpointUrl())
                    .credentials(minioProperties.getAccessKey(),minioProperties.getSecretKey()) //用户和密码
                    .build();


            boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());

            // 如果不存在，那么此时就创建一个新的桶
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {  // 如果存在打印信息
                System.out.println("Bucket 'spzx-bucket' already exists.");
            }
            //让用户上传唯一的图 id使用uuid 并且让图片分类更好的划分
            String dateDir = DateUtil.format(new Date(), "yyyyMMdd");
            //防止文件被覆盖
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            //类似  20240310/42ur24fg23401.jpg

            //get.filename 和 file.getOriginalFilename()
            System.out.println(file.getName());
            System.out.println(file.getOriginalFilename());

            String fileName = dateDir + "/"+ uuid + file.getOriginalFilename();

            minioClient.putObject(

                    PutObjectArgs.builder().bucket(minioProperties.getBucketName())
                            .object(fileName)
                            .stream(file.getInputStream(),file.getSize(), -1)
                            .build());
            //返回minio中上传过的文件地址
            //http://127.0.0.1:9000/spzx-bucket/course_id3.jpg
            String minioUrl = minioProperties.getEndpointUrl()+"/"+minioProperties.getBucketName()+"/"+fileName;

            return minioUrl;

        } catch (Exception e) {
            e.printStackTrace();
            throw  new XiaoXuException(ResultCodeEnum. SYSTEM_ERROR);
        }

    }
}













